package com.dl.mall.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.dl.mall.utils.JWTUtils;
import com.dl.mall.utils.result.Result;
import com.dl.mall.utils.result.ResultCodeEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author DL
 * @create 2022-03-13 18:20
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的令牌
        String token = request.getHeader("Authorization");

        //验证令牌
        Result result = null;
        try {
            DecodedJWT verify = JWTUtils.verify(token);
            String user_id = verify.getClaim("userId").asString();
            request.setAttribute("userId", user_id);
            request.setAttribute("token", token);

            return true;
        }catch (SignatureVerificationException e){//签名异常
            result = Result.error(ResultCodeEnum.TOKENS_SIGNATURE_EXCEPTION);
        }catch (TokenExpiredException ignored){//token过期异常
            result = Result.error(ResultCodeEnum.TOKENS_EXPIRE_EXCEPTION);
        }catch (AlgorithmMismatchException ignored){//算法不匹配异常
            result = Result.error(ResultCodeEnum.TOKENS_MISMATCH_EXCEPTION);
        }catch (Exception e){//token无效
            response.setStatus(403);
            result = Result.error(ResultCodeEnum.TOKENS_INVALID_EXCEPTION);
        }

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(result));
        return false;
    }
}
